package com.gollum.web.service.email;


import cn.hutool.core.convert.Convert;
import com.gollum.common.constant.NumberConstants;
import com.gollum.common.constant.SysConfigConstants;
import com.gollum.common.constant.SystemConstants;
import com.gollum.common.domain.email.Email;
import com.gollum.common.utils.MessageUtils;
import com.gollum.system.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Properties;

/**
 * 邮箱客户端 用于发送短信
 * @author Herther
 * @createTime 2022年11月05日 00:13:00
 * @since 1.0.0
 */
@Slf4j
@Component
@SuppressWarnings({"unchecked"})
public class EmailClient {


    @Autowired
    private SysConfigService sysConfigService;




    /**
     * 发送普通文本到邮箱
     *
     * @param email 邮箱参数
     * @auther: Herther
     * @since 1.0.0
     * @date: 2022/11/5 0:15
     */
    public void sendEmailTo(Email email) {
        // 普通邮箱发送
        Assert.notNull(email, MessageUtils.getMsg("email.send_param_fail"));
        JavaMailSenderImpl mailSender = buildMallSender();
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sysConfigService.getConfigValue(SysConfigConstants.EMAIL_BASIC_USERNAME));
        message.setTo(email.getReceives());
        message.setSubject(email.getSubject());
        message.setText(email.getContent());
        mailSender.send(message);
    }

    /**
     * 构建发送邮箱客户端
     *
     * @return JavaMailSenderImpl
     * @auther: Herther
     * @since 1.0.0
     * @date: 2022/11/5 23:31
     */
    public JavaMailSenderImpl buildMallSender(){
        JavaMailSenderImpl mallSender = new JavaMailSenderImpl();
        mallSender.setHost(sysConfigService.getConfigValue(SysConfigConstants.EMAIL_BASIC_HOST));
        mallSender.setDefaultEncoding(SystemConstants.UTF8);
        mallSender.setUsername(sysConfigService.getConfigValue(SysConfigConstants.EMAIL_BASIC_USERNAME));
        mallSender.setPassword(sysConfigService.getConfigValue(SysConfigConstants.EMAIL_BASIC_PASSWORD));
        mallSender.setPort(Convert.toInt(sysConfigService.getConfigValue(SysConfigConstants.EMAIL_BASIC_PORT), NumberConstants.TWENTY_FIVE));
        Properties mate = new Properties();
        //设置超时时间 25000毫秒
        mate.setProperty(SysConfigConstants.MAIL_SMTP_TIMEOUT, "25000");
        //让服务器进行认证,认证用户名和密码是否正确
        mate.setProperty(SysConfigConstants.MAIL_SMTP_AUTH,Convert.toStr(true));
        mallSender.setJavaMailProperties(mate);
        return mallSender;
    }
}
